import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'dart:convert';


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}


class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  int _currentIndex = 0; //当前页面索引
  String values = "";
  List<Widget> _pages = [Page1(), Page2(), Page3()]; //页面列表

  void _onTap(int index) { //切换页面的方法
    setState(() {
      _currentIndex = index;
    });
  }

  void _onPressed() async { //发送post请求的方法
    var url = Uri.http('example.com', '/post'); //请求地址
    var response = await http.post(url, body: {'name': 'Bing'}); //请求体
    print('Response status: ${response.statusCode}'); //打印响应状态码
    print('Response body: ${response.body}'); //打印响应内容
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('chatbot'),
      ),
      body: Center(
        child: _pages[_currentIndex],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: _onTap,
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '主页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.face_rounded ),
            label: '聊天',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.account_circle_rounded ),
            label: '我的',
          ),
        ],
      ),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: Center(
        child: Text('This is page one'),
      ),
    );
  }
}

class Page2 extends StatefulWidget {
  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<Page2> {
  final TextEditingController _controller = TextEditingController();
  List<String> _messages = [];
  bool _isLoading = false;
  void _sendMessage() async {
    String message = _controller.text;
    if (message.isNotEmpty) {
      setState(() {
        _messages.add(message); // 将输入框的内容添加到消息列表中
        _isLoading = true;
      });
      _controller.clear();
      try {

        // 使用client对象创建一个http.Client对象
        //http.Client proxyClient = http.Client.fromClient(client);
        var headers = {
          "Authorization": "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",
          "Content-Type": "application/json"
        };
        var body = { "query": message, "temperature": 0.9, "frequency_penalty": 0.5, "presence_penalty": 0.6, "best_of": 1, "stop": ["\n"] };
        var response = await http.post( Uri.parse("https://api.openai.com/v1/engines/davinci/completions"), headers: headers, body: jsonEncode(body));
        if (response.statusCode == 200) {
          var mbody = jsonDecode(response.body);
          var answer = mbody["choices"][0]["text"];
          print(answer);
          setState(() {
            _isLoading = false;
            _messages.add(answer);
          });
        } else {
          setState(() {
            _isLoading = false;
            _messages.add("返回消息错误");
          });
        }
      } catch (e) {
        setState(() {
          _isLoading = false;
          _messages.add("请求失败:$e");
        });
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('和chatgpt聊天'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                bool isMine = _messages[index].startsWith('我：');
                return Container(
                  alignment:
                  isMine ? Alignment.centerRight : Alignment.centerLeft,
                  color: isMine ? Colors.blue : Colors.green,
                  child: ListTile(
                    title: Text(_messages[index]),
                  ),
                );
              },
            ),
          ),
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _controller,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderSide:
                      BorderSide(width: 2.0, color: Colors.black),
                    ),
                  ),
                  enabled:
                  !_isLoading,
                ),
              ),
              ElevatedButton(onPressed:
              !_isLoading ?_sendMessage : null, child:
              const Text('发送')),
            ],
          ),
          if (_isLoading)
            const LinearProgressIndicator(),
        ],
      ),
    );
  }
}
class _Page2State extends State<Page2> {
  List<String> messages = []; // 定义一个字符串类型的列表，用来存储消息
  TextEditingController controller = TextEditingController(); // 定义一个文本控制器，用来获取输入框的内容
  void chatGPT() async {
    String message = controller.text; // 获取输入框的内容
    if (message.isNotEmpty) {
      setState(() {
        messages.add(message); // 将输入框的内容添加到消息列表中
      });
      controller.clear();
      try {
        var headers = {
          "Authorization": "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",
          "Content-Type": "application/json"
        };
        var body = { "query": message, "temperature": 0.9, "frequency_penalty": 0.5, "presence_penalty": 0.6, "best_of": 1, "stop": ["\n"] };
        var response = await http.post( Uri.parse("https://api.openai.com/v1/engines/davinci/completions"), headers: headers, body: jsonEncode(body));
        if (response.statusCode == 200) {
          var mbody = jsonDecode(response.body);
          var answer = mbody["choices"][0]["text"];
          print(answer);
          setState(() {
            messages.add(answer);
          });
        } else {
          setState(() {
            messages.add("返回消息错误");
          });
        }
      } catch (e) {
        setState(() {
          messages.add("请求失败:$e");
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            itemCount: messages.length, // 列表项的数量等于消息列表的长度
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(messages[index]), // 列表项显示消息列表中对应索引位置的内容
              );
            },
          ),
        ),
        Row(
          children: [
            Expanded(
              flex: 2,
              child: TextField(
                controller: controller,
              ),
            ),
            Expanded(
              flex: 1,
              child: ElevatedButton(onPressed: chatGPT, child: Text('发送')),
            ),
          ],
        ),

      ],
    );
  }
}

class Page3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
      child: Center(
        child:
        Text('This is page three'),
      ),
    );
  }
}
